/**
 * 
 */
package com.effectivsocial.rest.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.jaxrs.ext.MessageContext;
import org.springframework.beans.BeanUtils;
import org.springframework.social.twitter.api.DirectMessage;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.social.twitter.api.impl.TwitterTemplate;

import com.effectivsocial.domain.SocialNetwork;
import com.effectivsocial.rest.twitter.domain.SimpleDirectMessage;
import com.effectivsocial.rest.twitter.domain.SimpleTwitterProfile;

/**
 * @author Dhrubo
 * 
 */
public abstract class TwitterFactory {

	public static Twitter getTwitter(MessageContext context) {
		// TODO - Cache twitter instance

		SocialNetwork network = (SocialNetwork) context
				.getContextualProperty("network");
		Twitter twitter = new TwitterTemplate(network.getConsumerKey(),
				network.getConsumerSecret(), network.getAccessToken(),
				network.getAccessTokenSecret());

		return twitter;
	}

	public static SimpleDirectMessage getSimpleDirectMessage(
			DirectMessage directMessage) {
		SimpleDirectMessage simpleMessage = null;
		SimpleTwitterProfile sender = null;
		SimpleTwitterProfile recipient = null;

		simpleMessage = BeanUtils.instantiate(SimpleDirectMessage.class);
		sender = BeanUtils.instantiate(SimpleTwitterProfile.class);
		recipient = BeanUtils.instantiate(SimpleTwitterProfile.class);
		
		String ignoreProperties [] = {"sender", "recipient"};
		
		BeanUtils.copyProperties(directMessage, simpleMessage, ignoreProperties);
		BeanUtils.copyProperties(directMessage.getSender(), sender);
		BeanUtils.copyProperties(directMessage.getRecipient(), recipient);
		simpleMessage.setSender(sender);
		simpleMessage.setRecipient(recipient);

		return simpleMessage;
	}

	public static List<SimpleDirectMessage> getSimpleDirectMessages(
			List<DirectMessage> directMessages) {
		List<SimpleDirectMessage> simpleMessages = new ArrayList<SimpleDirectMessage>();
		for (DirectMessage directMessage : directMessages) {

			simpleMessages.add(getSimpleDirectMessage(directMessage));
		}
		
		return simpleMessages;
	}

}
